<template>
	<div id="sys_params">
		<main-head>
			<span slot="after">
				<el-button plain size="medium" @click="openDialog" type="primary" icon="el-icon-plus">添加文章</el-button>
			</span>
		</main-head>
		<main-content>
			<el-form :inline="true" :model="params" class="demo-form-inline">
				<!-- 表格顶部 -->
				<el-form-item label="创建日期">
					<el-date-picker v-model="date" type="datetimerange" range-separator="至" start-placeholder="开始日期"
						end-placeholder="结束日期" @change="dateSearch()">
					</el-date-picker>
				</el-form-item>
				<el-button type="primary" @click="search()">搜索</el-button>
			</el-form>

			<!-- 轮播图表格 -->
			<el-table :data="list" stripe style="width: 100%" v-loading="load">
				<el-table-column prop="id" label="id" align="center"></el-table-column>

				<el-table-column prop="title" label="文章标题" align="center"></el-table-column>
				<el-table-column prop="categoryName" label="分类类型" align="center">
				</el-table-column>
				
				<el-table-column :prop="avatar" label="主图" align="center" width="200">
					<template slot-scope="scope">
						<!-- {{fn(scope.row.avatar.split(','))}} -->
						<el-image style="width: 100px; height: 100px; border-radius: 50%" :src="scope.row.avatar"
							:preview-src-list="dealAva(scope.row.avatar)">
						</el-image>
					</template>
				</el-table-column>
				
				<el-table-column label="创建时间" align="center">
					<template slot-scope="scope">
						<span>{{$moment(scope.row.createTime).format("Y-MM-DD HH:mm")}}</span>
					</template>
				</el-table-column>

				<el-table-column label="操作" align="center" width="200">
					<template slot-scope="scope">
						<el-button type="primary" plain size="small" @click="openUpdateDialog(scope.row)">修改
						</el-button>
						<el-button type="danger" plain size="small" @click="deleteItem(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>


			<!-- 跳转地址 -->
			<el-dialog title="跳转地址" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
				<span>{{url}}</span>
				<span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
				</span>
			</el-dialog>



			<!-- 分页 -->
			<el-pagination class="page" background :layout="
          $store.state.isPhone
            ? 'total, prev, pager, next'
            : 'total, sizes, prev, pager, next, jumper'
        " :current-page.sync="params.pageNo" :page-size.sync="params.pageSize" :total="total" @size-change="search"
				@current-change="getList">
			</el-pagination>



			<!-- 添加dialog -->
			<el-dialog title="添加文章" :visible.sync="addDialog" width="50%">
				<el-form :model="addForm" :label-width="labelWidth" :rules="rule" ref="form">

					<el-form-item label="文章分类：" prop="categoryId">
						<el-select v-model="addForm.categoryId" clearable placeholder="选择文章类型">
							<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="主图:" prop="path">
						<upload ref="addAvatar" :limit_size="1" :isCompress="true" :bigBox="true"></upload>
					</el-form-item>
					<el-form-item label="视频:" prop="video">
						<video class="video" controls v-if="videoShow" :src="videoShow" width="30%" />
						<input ref="videoFile" @change="fileChange($event)" type="file" id="video_file"
							accept="video/*" />
						<el-button type="warning" @click="cleanFile()" size="mini">重置</el-button>
					</el-form-item>
					<el-form-item label="文章标题：" prop="title">
						<el-input placeholder="请输入分类描述" v-model="addForm.title" clearable>
						</el-input>
					</el-form-item>
					
					<el-form-item label="详情" prop="content">
						<editor :isClear="true" :value.sync="addForm.content" :uploadImgServer="this.uploadImg.url"
							@uploadSuccess="addFileUrl" @idUrl="setIdUrl"></editor>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button type="success" @click="add()">添加</el-button>
				</div>
			</el-dialog>


			<!-- 修改dialog -->
			<el-dialog title="修改文章" :visible.sync="updateDialog" width="50%">
				<el-form :model="updateForm" :label-width="labelWidth" :rules="rule" ref="update">

					<el-form-item label="文章分类：" prop="categoryId">
						<el-select v-model="updateForm.categoryId" clearable placeholder="选择文章类型">
							<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					
					<el-form-item label="主图:" prop="path">
						<upload ref="updateAvatar" :limit_size="1" :isCompress="true" :bigBox="true"></upload>
					</el-form-item>
					<el-form-item label="视频:" prop="video">
						<video class="video" controls v-if="videoShow" :src="videoShow" width="30%" />
						<input ref="videoFile" @change="fileChange($event)" type="file" id="video_file"
							accept="video/*" />
						<el-button type="warning" @click="cleanFile()" size="mini">重置</el-button>
					</el-form-item>
					<el-form-item label="文章标题：" prop="title">
						<el-input placeholder="请输入分类描述" v-model="updateForm.title" clearable>
						</el-input>
					</el-form-item>
					
					<el-form-item label="详情" prop="content">
						<editor :isClear="true" :value.sync="updateForm.content" :uploadImgServer="this.uploadImg.url"
							@uploadSuccess="addFileUrl" @idUrl="setIdUrl"></editor>
					</el-form-item>

				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button type="success" @click="updateItem()">修改</el-button>
				</div>
			</el-dialog>
		</main-content>
	</div>
</template>

<script>
	import Upload from '@/components/utils/Upload';
	import editor from '@/components/utils/CustomWangEditor';
	export default {
		components: {
			Upload,
			editor
		},
		data() {
			return {
				avatar:"",
				uploadImg: {
					url: "admin/adGoods/uploadImg",
					//存放返回的图片路径
					array: [],
					//关闭之前判断商品是否添加，未添加时为false，删除服务器图片
					addStatus: false
				},
				videoShow: false,
				dialogVisible: false, //跳转地址弹窗
				url: '',
				type: "",
				//表单Label宽度
				labelWidth: "100px",
				addForm: {
					sort: 0,
					type: "",

				},
				path: '',
				updateForm: {
					type: "",
				},
				addDialog: false,
				updateDialog: false,
				date: "",
				list: [],
				load: false,
				params: {
					pageSize: 10,
					pageNo: 1,
					isCount: true,
					startTime: "",
					endTime: "",
					type: 0,
				},
				options: [],
				total: 0,
				rule: {
					title: {
						message: "请填写文章标题",
						required: true,
					},
					content: {
						message: "请填写介绍详情",
						required: true,
					},

					categoryId: {
						message: "请输入序列号",
						required: true,
					},
				},
			};
		},

		mounted() {
			this.search();
			this.getCategoryList();
		},

		methods: {
			dealAva(e){
				return e.split(",")
			},
			// 跳转地址弹窗关闭
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						done();
					})
					.catch(_ => {});
			},
			//设置路径id
			setIdUrl(data) {
				this.uploadImg.url = "admin/adGoods/uploadImg";
				this.addForm.urlId = data
				this.updateForm.urlId = data
			},
			//存储图片url数组
			addFileUrl(data) {
				this.uploadImg.array.push(data);
			},
			getCategoryList() {
				let type = 4;
				this.$request.post({
					url: "system/sysCategory/listNoPage",
					params: {
						type
					},
					success: (result) => {
						this.options = result
					},
				});
			},

			search() {
				this.params.pageNo = 1;
				this.params.isCount = true;
				this.getList();
			},

			getList() {
				this.load = true;
				this.$request.post({
					url: "system/sysNews/list",
					params: this.params,
					success: (result) => {
						console.log(result);
						if (this.params.isCount) {
							this.total = result.total;
						}
						this.params.isCount = false;
						this.list = result.list;
					},
					finally: () => {
						this.load = false;
					},
				});
			},

			//时间改变
			dateSearch() {
				this.params.startTime = this.$moment(this.date[0]).format(
					"Y-MM-DD HH:mm:ss"
				);
				this.params.endTime = this.$moment(this.date[1]).format(
					"Y-MM-DD HH:mm:ss"
				);
				this.search();
			},
			//修改状态
			update(id) {
				let usId = id;
				this.$request.post({
					url: "admin/adUsInfo/updateStatus",
					params: {
						usId
					},
					success: (result) => {
						this.search();
					},
				});
			},
			cleanDialog() {
				this.addForm = {};
				this.updateFor = {};
				
			},
			openDialog(row) {
				this.videoShow = ""
				this.cleanDialog();
				this.addDialog = true;
				console.log(row);
				this.form = row;
			},
			//添加分类
			add() {
				this.videoShow = ""
				this.addForm.avatar = this.$refs.addAvatar.getPaths();
				this.$refs["form"].validate((valid) => {
					if (!valid) {
						return;
					}
					const loading = this.$loading({
					          lock: true,
					          text: 'Loading',
					          spinner: 'el-icon-loading',
					          background: 'rgba(0, 0, 0, 0.7)'
					        });
					const formData = new FormData();
					
					// 处理视频
					if (this.addForm.video instanceof File) {
						console.log("有视频")
					} else {
						if (this.addForm.video != undefined && this.addForm.video.indexOf(
								"file") != -1) {
							formData.append("hasVideo", true);
						}
					}
					
					formData.append("content", this.addForm.content);
					formData.append("avatar", this.addForm.avatar);
					formData.append("title", this.addForm.title);
					formData.append("video", this.addForm.video);
					formData.append("categoryId", this.addForm.categoryId);

					this.$request.post({
						url: "system/sysNews/saveOrUpdate",
						params: formData,
						success: (result) => {
							this.$message.success("添加成功");
							this.addDialog = false;
							this.cleanDialog();
							this.search();
							loading.close();
						},
						
					});
				});
			},

			//删除
			deleteItem(id) {
				this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				}).then(() => {
					this.$request.post({
						url: "system/sysNews/remove",
						params: {
							id
						},
						success: (result) => {
							this.$message.success(result);
							this.updateDialog = false;
							this.cleanDialog();
							this.search();
						},
					});
				});
			},
			
			// 打开修改框
			openUpdateDialog(row) {
				this.videoShow = ""
				this.cleanDialog();
				this.updateDialog = true;
				//浅拷贝
				this.updateForm = JSON.parse(JSON.stringify(row));
				console.log(this.updateForm);
				this.videoShow = this.updateForm.video;
				let avatar = this.updateForm.avatar.replace("[", "").replace("]", "");
				
				this.$nextTick(() => {
					this.$refs.updateAvatar.clean();
					this.$refs.updateAvatar.addPathList(avatar);
				});
				this.uploadImg = {
					url: "admin/adGoods/uploadImg?urlId=" + row.urlId,
					addStatus: false,
					array: []
				}
			},
			//修改分类
			updateItem() {
				this.$nextTick(() => {
					this.updateForm.path = this.$refs.updateAvatar.getPaths();
					this.$refs["update"].validate((valid) => {
						if (valid) {
							delete(this.updateForm.updateTime)
							delete(this.updateForm.createTime)
							
							const loading = this.$loading({
							          lock: true,
							          text: 'Loading',
							          spinner: 'el-icon-loading',
							          background: 'rgba(0, 0, 0, 0.7)'
							        });
							
							const formData = new FormData();
							
							if (this.updateForm.video instanceof File) {
								console.log("有视频")
							} else {
								if (this.updateForm.video != undefined && this.updateForm.video.indexOf(
										"file") != -1) {
									formData.append("hasVideo", true);
								}
							}
							
							formData.append("content", this.updateForm.content);
							formData.append("avatar", this.updateForm.avatar);
							formData.append("title", this.updateForm.title);
							formData.append("video", this.updateForm.video);
							formData.append("categoryId", this.updateForm.categoryId);
							formData.append("id", this.updateForm.id);

							this.$request.post({
								url: "system/sysNews/saveOrUpdate",
								params: formData,
								success: (result) => {
									this.$message.success(result);
									this.updateDialog = false;
									
									
									this.cleanDialog();
									this.search();
								},
								
							});
							loading.close();
						}
					})
				})
			},

			//视频上传
			fileChange(e) {
				var files = e.target.files || e.dataTransfer.files;
				if (!files.length) return;
				let name = files[0].name.toLowerCase();
				if (
					!/\.(avi|wmv|mpeg|mp4|mov|mkv|flv|f4v|m4v|rmvb|rm|3gp|dat|ts|mts|vob)$/.test(
						name
					)
				) {
					this.$message.warning("请上传视频");
					return;
				}
				if (files[0].size > 1024 * 1024 * 20) {
					this.$message.warning("视频大小不能大于20M");
					return;
				}
				this.updateBan = true;
				this.addForm.video = files[0];
				this.updateForm.video = files[0];
				var reader = new FileReader();
				reader.readAsDataURL(files[0]);
				reader.onload = () => {
					//视频回显用
					this.videoShow = reader.result;
					this.updateBan = false;
				};
			},
			cleanFile() {
				this.updateForm.video = "",
					this.addForm.video = "",
					this.videoShow = ""
			},
		},
	};
</script>

<style>
</style>

<style scoped>
	.page {
		text-align: right;
		margin-top: 20px;
	}
</style>
